package filter

import (
	"github.com/astaxie/beego/context"
	"github.com/dgrijalva/jwt-go"
	"public_security/databases"
	"public_security/models"
	"public_security/tools"
	"strings"
)

var UserFilterFunc = func(ctx *context.Context) {
	if !strings.Contains(ctx.Request.RequestURI, "/login") && !strings.Contains(ctx.Request.RequestURI, "/query") && !strings.Contains(ctx.Request.RequestURI, "/upload") && !strings.Contains(ctx.Request.RequestURI, "/controller") {
		token := ""
		if ctx.Request.Header.Get("Authorization") != "" {
			token = ctx.Request.Header.Get("Authorization")
		} else if ctx.Request.Header.Get("Token") != "" {
			token = ctx.Request.Header.Get("Token")
		} else if ctx.Request.Header.Get("token") != "" {
			token = ctx.Request.Header.Get("token")
		} else {
			cookie, _ := ctx.GetSecureCookie(tools.JwtKey, "Authorization")
			token = cookie
		}
		if token == "" {
			ctx.ResponseWriter.WriteHeader(401)
			ctx.ResponseWriter.Write([]byte("no permission"))
		} else {
			if !checkLogin(token, ctx) {
				ctx.ResponseWriter.WriteHeader(401)
				ctx.ResponseWriter.Write([]byte("未登录，请登录"))
			}
			if !judgeUser(tools.NewAuthTool(), token, ctx) {
				ctx.ResponseWriter.WriteHeader(401)
				ctx.ResponseWriter.Write([]byte("未登录，请登录"))
			}
		}

	}

}

func checkLogin(token string, ctx *context.Context) bool {
	if !tools.NewAuthTool().CheckToken(token) {
		return false
	} else {
		mapClaims := tools.NewAuthTool().ParseKey(token).Claims.(jwt.MapClaims)
		if v, ok := mapClaims["loginType"]; ok {
			if v == "user" {
				user := new(models.Users)
				user.Token = token
				id := int(mapClaims["id"].(float64))
				databases.DbDefault.Model(&models.Users{}).Where("id=?", id).First(&user)
				ctx.Input.SetData("user", user)
			}
		}
	}
	return true
}
func judgeUser(auth *tools.AuthTool, token string, ctx *context.Context) bool {
	mapClaims := auth.ParseKey(token).Claims.(jwt.MapClaims)
	if v, ok := mapClaims["loginType"]; ok {
		//新生成的token
		if v == "user" {
			user := new(models.Users)
			id := int(mapClaims["id"].(float64))
			databases.DbDefault.Model(&models.Users{}).Where("id=?", id).First(&user)
			//if token != user.Token {
			//	logs.Warning("token 与数据库中不一致", token)
			//	return false
			//}
			ctx.Input.SetData("user", user)
		}
	}
	return true
}
